package org.kong.security;


import org.kong.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 这个方法是重写的是UserDetailsService的方法
     * 自定义的校验规则
     * 通过username加载用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 通过username查询用户信息
         */
        org.kong.pojo.entity.User user = userMapper.loginByUsername(username);

        /**
         * 校验用户信息,若用户不存在,则抛出UsernameNotFoundException异常
         */
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        /**
         * 使用AuthorityUtils将字符串转换为GrantedAuthority对象
         * 这里的字符串是用户的权限信息,每个权限之间用逗号隔开
         * 这个是在用户中定义的权限,不应是写死的,应查询数据库,我这里是暂时测试了一下
         */
        // List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("add,update");

        /**
         * 从数据库中查询用户的权限信息
         */
        Set<String> auths = userMapper.getAuthsById(user.getId());

        /**
         * 打印用户的权限信息
         */
        System.out.println(auths);

        Set<GrantedAuthority> authorities = new HashSet<>();

        auths.forEach(item->authorities.add(new SimpleGrantedAuthority(item)));

        authorities.add(new SimpleGrantedAuthority("ROLE_超级管理员"));

        System.out.println("authorities = " + authorities);

        /**
         * 返回UserDetails对象
         * 这里的UserDetails对象是SpringSecurity提供的类,用于封装用户信息
         */
        return new User(user.getUsername(), user.getPassword(), authorities);
    }
}

